package ThreadPoolDemo.bilibiliThread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo {

	private Map<String, Object> cache = new HashMap<String, Object>();

	public static void main(String[] args) {

	}

	/**
 * 
 */
	private ReadWriteLock rwlLock = new ReentrantReadWriteLock();

	public Object getData(String key) {
		rwlLock.readLock().lock();
		Object object = null;
		try {
			object = cache.get(key);
			if (null == object) {
				rwlLock.readLock().unlock();// 并发时，要先unlock
				rwlLock.writeLock().lock();
				try {
					if (null == object) {// 防止并发线程获取写锁后，再查一次数据
						object = "zzy";// 实际是去querydb();
					}

				} finally {
					rwlLock.writeLock().unlock();
				}
				rwlLock.readLock().lock();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwlLock.readLock().unlock();
		}

		return object;
	}
}
